package com.imooc.alllearning.service.impl;

import com.imooc.alllearning.exception.BusinessException;
import com.imooc.alllearning.exception.ErrorCodeEnum;
import com.imooc.alllearning.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.*;

/**
 * 本地文件上传服务实现类
 * @Author: crowsjian
 * @Date: 2020/4/1 19:31
 */
@Slf4j
@Service("localFileServiceImpl")
public class LocalFileServiceImpl implements FileService {
    /**
     * 存储空间
     */
    private static final String BUCKET = "uploads";
    @Override
    public void upload(InputStream inputStream, String filename) {
        //拼接文件存储地址
        String storagePath = BUCKET+"/"+filename;
        try(
                // JDK8 TWR 不能关闭外部资源
                InputStream innerInputStream = inputStream;
                FileOutputStream outputStream = new FileOutputStream(new File(storagePath))
                ){
            // 拷贝缓存区
            byte[] buffer = new byte[1024];
            // 读取文件流长度
            int len;
            //循环读取inputStream中数据写入到outputStream
            while((len = inputStream.read(buffer))>0){
                outputStream.write(buffer, 0, len);
            }
            //冲刷流
            outputStream.flush();
        }catch (Exception e){
            log.error("文件上传失败！",e );
            throw new BusinessException(ErrorCodeEnum.UPLOAD_FILE_ERROR, e);
        }
    }

    @Override
    public void upload(File file) {
        try {
            upload(new FileInputStream(file), file.getName());
        } catch (FileNotFoundException e) {
            log.error("文件上传失败！",e );
            throw new BusinessException(ErrorCodeEnum.UPLOAD_FILE_ERROR, e);
        }
    }
}
